<?php
namespace model;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use session\UserSession;
use model\Query;
use controller\GameController;
use controller\SocketController;



class SocketComunication implements MessageComponentInterface {
    protected $clients;
	
    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
       	$conn->send('{"type": "resourceId","value": "' . md5($conn->resourceId) . '"}');
     
        echo "New connection! ({$conn->resourceId})\n";
       	
        $file = fopen('resourseId.txt', 'a+');	
		fwrite($file, $conn->resourceId . ',');	
		fclose($file);
        
    }

    public function onMessage(ConnectionInterface $from, $msg) {
    	echo "\n $msg";
        $numRecv = count($this->clients) - 1;
        $json = json_encode($msg); 
        $jsonDecoded = json_decode($msg,true); 
       	
        if (isset($jsonDecoded['type']))  {
       			if ($jsonDecoded['type'] == "teritory") {
       					$notSameTeritory = false;
       					$msgSent = $jsonDecoded['area'];
       					$t = $msgSent[4];
       					if ($t >= 1 && $t <= 9) {	
			        		$from->teritorySelected = $t;
			        		 foreach ($this->clients as $client) {
			        			if ($client->userId == $from->connectWith) {
			        				if ($t != $client->teritorySelected) {
				        				$secondPlayer = $client;
				        				$from->send('{"type": "teritory", "area": "area' . $t .'", "color": "select"}');
				        				$secondPlayer->send('{"type": "teritory", "area": "area' . $t .'", "color": "blue"}');
				        				$notSameTeritory = true;
			        				}
			        			}
			        		} 
			        		if ($notSameTeritory) {
				        		if ($from->round > $secondPlayer->round) {
				        			$secondPlayer->round++;
				        			$secondPlayer->send('{"type": "selectTeritory"}');
				        			$secondPlayer->timeSendSelectTeritory = time();
				        			$from->send('{"type": "waitingSelecting"}');
				        		} else {
				        			if ($from->round == $secondPlayer->round) {
					        				if($from->round <= 4) {
					        				$gameController = new SocketController();
					        				$question = $gameController->getQuestionMessage(1, 1);
					        				$from->questionId = $gameController->getQuestionId();
					        				echo "\n Question id saved is: " . $from->questionId;
					        				$secondPlayer->questionId = $gameController->getQuestionId();
						        			$secondPlayer->send($question);
						        			$secondPlayer->timeSendQuestion = time();
						        			$from->timeSendQuestion = time();
						        			$from->send($question);
						        			
						        			// switch turns
						        			
						        			$from->turn = abs($from->turn - 1);
						        			$secondPlayer->turn = abs($secondPlayer->turn - 1);
					        				} else {
					        					// vapros tip 2
					        				}
				        			}  
				        		}
			        		} 	
       					}	
        		}
        		if ($jsonDecoded['type'] == "broadcast") {
        			$msgSent = $jsonDecoded['usermsg'];
        			$user = $jsonDecoded['username'];
        			$date = new \DateTime();
        			$date->setTimezone(new \DateTimeZone('Europe/Sofia'));
        			$nowtime = $date->format('H:i:s');
        			foreach ($this->clients as $client) {
        				if($msgSent != ""){
        					$client->send('{"type": "broadcastChat", "msg": "[' . $nowtime . '] ' . $user . ':  ' . $msgSent. '"}');
        					echo "\n sending msg";
        				}
        			}
        		}
        		if ($jsonDecoded['type'] == 'checkAnswer') {
        			$gameController = new SocketController();
        			$correct = $gameController->getCorrectAnswer($from->questionId);
        			echo "\n Question looking for right answer: " . $from->questionId;
        			$queryEngine = new Query();
        			if ($this->checkDelay($from->timeSendQuestion) > 16 * 1000) {
        				$from->send('{"type": "correctAnswer", "isCorrect": "Времето изчече за ", "correct": "' . $correct['answer_text'] .'"}');
        				$from->send('{"type": "teritory", "area": "area' . $from->teritorySelected .'", "color": "yellow"}');
        				$from->second->send('{"type": "teritory", "area": "area' . $from->teritorySelected  .'", "color": "yellow"}');
        			} 
        			else if ($jsonDecoded['answer'] == $correct['answer_id']) {
        				$from->send('{"type": "correctAnswer", "isCorrect": "Верен", "correct": "' . $correct['answer_text'] .'"}');  				
        				$queryEngine->updateTeritory(1, $from->teritorySelected , $from->userId);
        				$from->send('{"type": "teritory", "area": "area' . $from->teritorySelected .'", "color": "green"}');
        				$from->second->send('{"type": "teritory", "area": "area' . $from->teritorySelected  .'", "color": "grey"}');
        			} else {
        				$from->send('{"type": "correctAnswer", "isCorrect": "Грешен", "correct": "' . $correct['answer_text'] .'"}');
        				$from->send('{"type": "teritory", "area": "area' . $from->teritorySelected .'", "color": "yellow"}');
        				$from->second->send('{"type": "teritory", "area": "area' . $from->teritorySelected  .'", "color": "yellow"}');
        			}
        		}
        		if ($jsonDecoded['type'] == 'getAction') {
        			
        			if ($from->turn == 1) {
        				$from->send('{"type": "waitingSelecting"}');
        			} else {
        				$from->send('{"type": "selectTeritory"}');
        				$from->timeSelectedTeritory = time();
        				$from->round++;
        			}
        		}
        		if ($jsonDecoded['type'] == "infoForUser") {
        			$this->setUserId($from, $jsonDecoded['userId']);
        		}
        		if ($jsonDecoded['type'] == "sendTo") {
        			echo "\n message sending";
        			foreach ($this->clients as $client) {
        				if ($client->userId == $from->connectWith) {
        					echo "\n message send";
        					$client->send($msg);
        				}
        			}
        		}
        		if ($jsonDecoded['type'] == "userId") {
        		//	echo "vliza v ifa";
        			$md5UserId = $jsonDecoded['id'];
        			$isThereUser = false;
        			$file = fopen('userId.txt', 'r');
        			$conns = fread($file, 10);
        			fclose($file);
        			$file = fopen('userId.txt', 'w');
        			$conn = explode(',', $conns);
        			foreach ($conn as $value) {
        				if (is_numeric($value)) {
        					if (md5($value) == $md5UserId) {
        						$isThereUser = $value;
        					} else
        						fwrite($file, $value . ',');
        				}
        			}
        			fclose($file);
        			if ($isThereUser != false) {
        				$from->userId = $isThereUser;
        				echo "\n ConnectionId: {$from->resourceId} and UserId: {$from->userId} ";
        			}
        		}
        		if ($jsonDecoded['type'] == "connectWith") {
        			$from->connectWith=$jsonDecoded['id'];
        			echo "\nConnection between two established";
        			$from->teritorySelected= 0;
        			foreach ($this->clients as $client) {
        				if ($client->userId == $jsonDecoded['id']) {
        					$client->connectWith = $from->userId;
        					$secondPlayer = $client;
        					$from->second = $client;
        					$client->second = $from;
        					$secondPlayer->teritorySelected = 0;
        				}
        			}
        			$from->second->send('{"type": "confirmGame"}');	
        		}
        		if ($jsonDecoded['type'] == "startGame") {
        			echo"\n vlizam";
        			foreach ($this->clients as $client) {
        				if ($client->connectWith == $from->userId) {
        					$client->send('{"type": "renderGame"}');
        					$client->turn = 1;
        					$client->round = 0;
        					$client->send('{"type": "waitingSelecting"}');
        				}
        			}
        				$from->send('{"type": "renderGame"}');
        				$from->turn = 0;
        				$from->round = 1;
        				$from->send('{"type": "selectTeritory"}');
        				$from->timeSelectedTeritory = time();
        				echo "sending select teritory";
        			
        		}
        }
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
      //  var_dump(self::$connections);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }
    
    private function setUserId(ConnectionInterface $conn, $md5UserId) {
    	
    }
    
    private function checkDelay($timeSent) {
    	return time() - $timeSent;
    }
}